<?php
/*
 * IKPHP 爱客开源社区 @copyright (c) 2012-3000 IKPHP All Rights Reserved 
 * @author 小麦
 * @Email:ikphp@sina.cn
 * @爱客网特有ikmail消息组件系统 下期继续优化
 */
namespace IKPHP\Apps\Home\Controllers;

use IKPHP\Common\Controllers\FrontendController;
use IKPHP\Common\Models\User;
use IKPHP\Org\UploadFile;
use IKPHP\Common\Models\Images;

class ImagesController extends FrontendController {
	
	private $userid = 0;

    public function initialize()
    {
        parent::initialize();
    	// 访问者控制
		if ($this->visitor){
			$this->userid = $this->visitor['userid'];
		}
		
		$this->user_mod =  new User();
		$this->_mod = new Images();		
    }
    public function addAction(){
		if(IS_POST && IS_AJAX){
			$isRemote = $this->_post('isRemote','intval','0');
			if($isRemote){ return $this->uploadRemote();}
	 		$typeid  = $this->_post('typeid','intval','0');
			$type = $this->_post('type','trim');
			$userid = $this->userid;   
			if($this->request->hasFiles() == true && $userid>0){
				//类型判断
				$up_files = $this->request->getUploadedFiles();
				$up_file = $up_files[0];
				$up_file_type = $up_file->getType();
				
				//类型判断
				if($up_file_type !== 'image/png' && $up_file_type !== 'image/jpeg')
				{
					$arrJson = array('r'=>1, 'html'=> '图像类型不符；只允许上传jpeg、jpg、png类型图片');
					echo json_encode($arrJson, true);	
				}
				
				//大小判断
				if($up_file->getSize()/1024 > 2048)
				{
					$arrJson = array('r'=>1, 'html'=> '图片不允许大于2M');
					echo json_encode($arrJson, true);						
				}	

				//保存文件夹
	            $data_dir = date ( 'Y/md/H' );
	            $avatar_dir = $type . '/' . $data_dir.'/';
	            
				//开始保存
				$upload = new UploadFile(array('autoSub'=>false,'savePath'=>$avatar_dir));
				$result = $upload->upload(); 
				if(!empty($result)){
									
					$imgpath = C('ik_attach_path').$result[0]['savefile'];
					$image = new \IKPHP\Org\Image();
					//打开图像生成thumb
					try {
						//获取配置头像大小
						$strimgs = C('ik_simg.width').','.C('ik_mimg.width').','.C('ik_bimg.width');
						$arr_size = explode(',', $strimgs);         
			            //打开图像
			            foreach ($arr_size as $item){
			            	$image->open($imgpath);
			            	$thumb_name = $result[0]['filename'].'_'.$item.'_'.$item.'.'.$result[0]['ext']; //文件名
			            	$thumb_img = C('ik_attach_path').$result[0]['savepath'].$thumb_name;//保存路径
			            	$image->thumb($item, $item)->save($thumb_img);
			            }
			            //更新数据库
						$name = $result[0]['savename'];
						$path = $result[0]['savepath'];
						$size = $result[0]['size'];
						$title = $result[0]['name'];
						$photoid = $this->_mod->addImage($name,$path,$size,$title,$type,$typeid,$userid);
						//浏览该$photoid下的照片
						$arrPhoto = $this->_mod->getImageById($photoid);
						$arrJson = array(
								'id'=> $photoid,
								'layout'=> $arrPhoto['align'],
								'title'=>'',
								'seq_id'=> $arrPhoto['seqid'],
								'small_photo_url'=> $arrPhoto['simg'],
								'ajaxurl' => U('home/images/delete'),
						);
						echo json_encode($arrJson, true);		            
			            
					} catch(\Exception $e) {
						$arrJson = array('r'=>1, 'html'=> $e->getMessage());
						echo json_encode($arrJson, true);	
					}
					
					
				}else{
					$arrJson = array('r'=>1, 'html'=> '服务器忙上传失败！');
					echo json_encode($arrJson, true);					
				}
					
			}else{
				$arrJson = array('r'=>1, 'html'=> '请选择图片再上传！');
				echo json_encode($arrJson, true);
			}
			$this->view->disable();	
		}else{
			return $this->error('呃...你没有权限访问该页面');
		}
    }
    /**
     * array (size=9)
     * 'size' => float 381.03515625
     * 'name' => string 'test.jpg' (length=8)
     * 'ext' => string 'jpg' (length=3)
     * 'tmp_name' => string 'D:\wamp\tmp\php7EA4.tmp' (length=23)
     * 'md5' => string '2fcdd5beaedbcaa49535099e7cced5da' (length=32)
     * 'sha1' => string '48dc94d82046c6ee3a812b0efcfcf9c65096377c' (length=40)
     * 'filename' => string 'c81e728d9d4c2f636f067f89cc14862c' (length=36)
     * 'savename' => string 'c81e728d9d4c2f636f067f89cc14862c.jpg' (length=36)
     * 'savepath' => string 'face/000/00/00/' (length=15)
     * 'savefile' => string 'face/000/00/00/c81e728d9d4c2f636f067f89cc14862c.jpg' (length=51)
     * */     
    //上传远程图片
    public function uploadRemote(){
    	
    	$result = array('size'=>'','name'=>'','ext'=>'','savename'=>'','savepath'=>'','savefile'=>'');
    	
		$isRemote = $this->_post('isRemote','intval','0');
 		$typeid  = $this->_post('typeid','intval','0');
		$type = $this->_post('type','trim');
		$userid = $this->userid; 
		$filepath = $this->_post('filepath','trim','');
		
		if(IS_POST&&IS_AJAX){
			if($isRemote==0){
				$arrJson = array('r'=>1, 'html'=> '不是远程图片');
				return $this->ajaxReturn($arrJson);
			}
			if($userid>0 && !empty($typeid) && !empty($type) && !empty($filepath)){

				$ext = fileext($filepath);//得到后缀
				
				if(!in_array($ext, array('jpg', 'jpeg', 'gif', 'png'))) {
					$arrJson = array('r'=>1, 'html'=> '抓取的远程图片类型不正对,必须是：'."'jpg', 'jpeg', 'gif', 'png'");
					return $this->ajaxReturn($arrJson);						
				}

				$result['ext'] = $ext; 
				$result['name'] = '网络图片'; 
				
				//debug 上传
				$content = sreadfile($filepath, 'rb', 1, 0);
				if(empty($content)){
					$arrJson = array('r'=>1, 'html'=> '抓失败可能是数据有误');
					return $this->ajaxReturn($arrJson);					
				}
				$result['filename'] = gmdate('YmdHis',time() + C('ik_timezone') * 3600).random(4);
				$result['savename'] = $result['filename'].'.'.$ext; 
	
				//保存文件夹
	            $data_dir = date ( 'Y/md/H' );
	            $avatar_dir = $type . '/' . $data_dir.'/';
	            $result['savepath'] = getattachdir($avatar_dir);
	            $result['savefile'] = $result['savepath'].$result['savename'];

	            //开始保存
	            writefile(C('ik_attach_path').$result['savefile'], $content, 'text', 'wb', 0);
				if(!file_exists(C('ik_attach_path').$result['savefile'])){
					$arrJson = array('r'=>1, 'html'=> '写数据失败');
					return $this->ajaxReturn($arrJson);							
				}

				//图片类型判断	
				$imageinfo = @getimagesize(C('ik_attach_path').$result['savefile']);
				list($width, $height, $imgtype) = !empty($imageinfo) ? $imageinfo : array('', '', '');
				if(!in_array($imgtype, array(1,2,3,6,13))) {
					@unlink(C('ik_attach_path').$result['file']);
					$arrJson = array('r'=>1, 'html'=> '不是有效的图片文件');
					return $this->ajaxReturn($arrJson);	
				}

				$result['size'] = filesize(C('ik_attach_path').$result['savefile']);
				
				//开始入库
			
			if(!empty($result)){
									
					$imgpath = C('ik_attach_path').$result['savefile'];
					$image = new \IKPHP\Org\Image();
					//打开图像生成thumb

					//获取配置头像大小
					$strimgs = C('ik_simg.width').','.C('ik_mimg.width').','.C('ik_bimg.width');
					$arr_size = explode(',', $strimgs);         
		            //打开图像
		            foreach ($arr_size as $item){
		            	$image->open($imgpath);
		            	$thumb_name = $result['filename'].'_'.$item.'_'.$item.'.'.$result['ext']; //文件名
		            	$thumb_img = C('ik_attach_path').$result['savepath'].$thumb_name;//保存路径
		            	$image->thumb($item, $item)->save($thumb_img);
		            }
		            //更新数据库
					$name = $result['savename'];
					$path = $result['savepath'];
					$size = $result['size'];
					$title = $result['name'];
					$photoid = $this->_mod->addImage($name,$path,$size,$title,$type,$typeid,$userid);
					//浏览该$photoid下的照片
					$arrPhoto = $this->_mod->getImageById($photoid);
					$arrJson = array(
							'id'=> $photoid,
							'layout'=> $arrPhoto['align'],
							'title'=>'',
							'seq_id'=> $arrPhoto['seqid'],
							'small_photo_url'=> $arrPhoto['simg'],
							'ajaxurl' => U('home/images/delete'),
					);
					
					return $this->ajaxReturn($arrJson);		            

				}else{
					$arrJson = array('r'=>1, 'html'=> '服务器忙上传失败！');
					return $this->ajaxReturn($arrJson);					
				}			
			
			}else{
				$arrJson = array('r'=>1, 'html'=> '数据有误');
				return $this->ajaxReturn($arrJson);			
			}
						
		}else{
			$arrJson = array('r'=>1, 'html'=> '不是远程图片');
			return $this->ajaxReturn($arrJson);
		}
    }
	// 删除图片
	public function deleteAction(){
		if(IS_POST){
			$site_ck = $this->_post('ck','trim');
			$id = $this->_post('id','intval');
			$seqid = $this->_post('seq_id','intval');
			if($this->visitor['site_ck'] == $site_ck){
				$res = Images::delImage($id);
				$arrJson = array('r'=>0, 'html'=> '删除成功');
				return $this->ajaxReturn($arrJson);		
			}else{
				$arrJson = array('r'=>1, 'html'=> '删除失败');
				return $this->ajaxReturn($arrJson);				
			}
		}
	}
}